var mapPopControl = {};
var wms, map, pzb, markers, layer, geocoder;
var labelList = [], markerList = [], popupCloud = null;
var Options, tabOptions;
var clickCheck = 0;
var SHADOW_Z_INDEX = 10;
var MARKER_Z_INDEX = 11;


var DIAMETER = 200;
var NUMBER_OF_FEATURES = 15;


//Accepts a url and a callback function to run.
function requestCrossDomain( site, callback ) {

	// If no url was passed, exit.
	if ( !site ) {
		alert('No site was passed.');
		return false;
	}

	// Take the provided url, and add it to a YQL query. Make sure you encode it!
	// var yql = 'http://query.yahooapis.com/v1/public/yql?q=' + encodeURIComponent('select * from html where url="' + site + '"') + '&format=xml&callback=?';
	// alert(yql);
	// alert(site);
	var crossDomainURL = "/umanji_dev/umj/util/crossDomainAjaxPage?url=" + site
	// Request that YSQL string, and run a callback function.
	// Pass a defined function to prevent cache-busting.
	$.getJSON( crossDomainURL, cbFunc );

	function cbFunc(data) {
		// If we have something to work with...
		if ( data.results[0] ) {
			// Strip out all script tags, for security reasons.
			// 	BE VERY CAREFUL. This helps, but we should do more.
			data = data.results[0].replace(/<script[^>]*>[\s\S]*?<\/script>/gi, '');

			// If the user passed a callback, and it
			// is a function, call it, and send through the data var.
			if ( typeof callback === 'function') {
				callback(data);
			}
		}
		// Else, Maybe we requested a site that doesn't exist, and nothing returned.
		else throw new Error('Nothing returned from getJSON.');
	}
}

/**
 * Function: addMarker
 * Add a new marker to the markers layer given the following lonlat, 
 *     popupClass, and popup contents HTML. Also allow specifying 
 *     whether or not to give the popup a close box.
 * 
 * Parameters:
 * ll - {<OpenLayers.LonLat>} Where to place the marker
 * popupClass - {<OpenLayers.Class>} Which class of popup to bring up 
 *     when the marker is clicked.
 * popupContentHTML - {String} What to put in the popup
 * closeBox - {Boolean} Should popup have a close box?
 * overflow - {Boolean} Let the popup overflow scrollbars?
 */
function addMarker(ll, popupClass, popupContentHTML, closeBox, overflow) {

    var feature = new OpenLayers.Feature(markers, ll); 
    feature.closeBox = closeBox;
    feature.popupClass = popupClass;
    feature.data.popupContentHTML = popupContentHTML;
    feature.data.overflow = (overflow) ? "auto" : "hidden";
            
    var marker = feature.createMarker();

    var markerClick = function (evt) {
        if (this.popup == null) {
            this.popup = this.createPopup(this.closeBox);
            map.addPopup(this.popup);
            this.popup.show();
        } else {
            this.popup.toggle();
        }
        currentPopup = this.popup;
        OpenLayers.Event.stop(evt);
    };
    marker.events.register("mousedown", feature, markerClick);

    markers.addMarker(marker);
}


function getInitializedMap(lonlat){
	OpenLayers.IMAGE_RELOAD_ATTEMPTS = 5;
	OpenLayers.DOTS_PER_INCH = 90.71428571428572;

	AutoSizeFramedCloud = OpenLayers.Class(OpenLayers.Popup.FramedCloud, {
        'autoSize': true
    });

    AutoSizeFramedCloudMinSize = OpenLayers.Class(OpenLayers.Popup.FramedCloud, {
        'autoSize': true, 
        'minSize': new OpenLayers.Size(400,400)
    });

    AutoSizeFramedCloudMaxSize = OpenLayers.Class(OpenLayers.Popup.FramedCloud, {
        'autoSize': true, 
        'maxSize': new OpenLayers.Size(100,100)
    });

	OpenLayers.Util.onImageLoadErrorColor = 'transparent';

	var mapOptions = { 
		div: "map",
		resolutions: [2240.0, 1120.0, 560.0, 280.0, 140.55999999999997, 70.27999999999999, 35.279999999999994, 17.639999999999997, 8.68, 4.4799999999999995, 2.19744, 1.09872, 0.54936, 0.27468, 0.1316, 0.0658],
		projection: new OpenLayers.Projection('EPSG:900913'),
		displayProjection: new OpenLayers.Projection("EPSG:4326"),
		maxExtent: new OpenLayers.Bounds(1.2975869998193746E7,3686148.999486882,1.5843069998193746E7,5979908.999486882),
		units: "m",
        controls: [new OpenLayers.Control.Navigation(),
                   new OpenLayers.Control.MouseDefaults(),
                   new OpenLayers.Control.MousePosition({numdigits:2}),                
                   new OpenLayers.Control.PanZoomBar(),
                   new OpenLayers.Control.Permalink('permalink'),                         
                   new OpenLayers.Control.ScaleLine()
                   ]
	};

	// 구글 geocoder 생성
	geocoder = new google.maps.Geocoder();

	// $("#map").width( parseInt($(window).width()) - parseInt($(".column.fixed.sidebar").width()) );
	$("#map").width( 720 );
	$("#map").height( 408 );

	map = new OpenLayers.Map( mapOptions );

	// 쉐도우 마커 생성을 위한 레이어
    layer = new OpenLayers.Layer.Vector(
            "Marker Drop Shadows",
            {
                styleMap: new OpenLayers.StyleMap({
                    externalGraphic: "/umanji_dev/images/map/marker/marker-gold.png",
                    backgroundGraphic: "/umanji_dev/images/map/marker/marker_shadow.png",
                    backgroundXOffset: 0,
                    backgroundYOffset: -7,
                    graphicZIndex: MARKER_Z_INDEX,
                    backgroundGraphicZIndex: SHADOW_Z_INDEX,
                    pointRadius: 10
                }),
                isBaseLayer: false,
                rendererOptions: {yOrdering: true}
            }
    );

	wms = new OpenLayers.Layer.WMS(
					"umanji","http://www.umanji.com/geowebcache/service/wms",
					{layers: 'umanji', format: 'image/png' },
					{ isBaseLayer: true, tileSize: new OpenLayers.Size(256,256), projection: new OpenLayers.Projection('EPSG:900913') }
	);

	// 등록된 마커 리스트 뿌리기 위한 레이어
	markers = new OpenLayers.Layer.Markers("zibo");

    map.addLayers([wms, layer, markers]);

	map.zoomToExtent(new OpenLayers.Bounds(1.2975869998193746E7,3686148.999486882,1.5280145997872988E7,5543121.999228389));
	map.setCenter(lonlat, 12);

	return map;
    /*
    map.events.register('click', map, function (e) {
        document.getElementById('nodelist').innerHTML = "Loading ... please wait ...";
        var params = {	REQUEST: "GetFeatureInfo",
        				EXCEPTIONS: "application/vnd.ogc.se_xml",
        				BBOX: map.getExtent().toBBOX(),
        				X: e.xy.x,
        				Y: e.xy.y,
        				INFO_FORMAT: 'application/vnd.ogc.gml',
        				QUERY_LAYERS: 'umanji:building', // map.layers[0].params.LAYERS,
        				FEATURE_COUNT: 50,
        				Srs: 'EPSG:900913', //EPSG%3A900913
        				Layers: 'umanji:building',
        				Styles: '',
        				WIDTH: map.size.w,
        				HEIGHT: map.size.h	};
        OpenLayers.loadURL("http://www.umanji.com/geoserver/wms", params, this, setHTML);
    	// window.open("http://hboard.iwk.uni-karlsruhe.de:8080/geoserver/wms?service=WMS&version=1.1.0&request=GetMap&layers=Moskva&styles=&bbox=-125830.05,6099218.02,153008.285,6277080.521&width=517&height=330&srs=EPSG:32638&format=application/openlayers");
        OpenLayers.Event.stop(e);
    });


	searchEvent();
	map.events.register("moveend", map, function(e) {
    	mapAreaSearch();
    	searchEvent();
    	mapPopControl.ContentPrint($("#searchMode").val());
    	if($("#searchMode").val() != "home") $('#searchForm').ajaxSubmit(tabOptions);
        OpenLayers.Event.stop(e);
    });
    */
}

function getPopupFeature(layer, lonlat) {
    var popupFeature = new OpenLayers.Feature({layer: layer, lonlat: lonlat});
    popupFeature.closeBox = true;
    popupFeature.popupClass = AutoSizeFramedCloud;
    popupFeature.data.popupContentHTML = '';
    popupFeature.data.overflow = "auto"; // (overflow) ? "auto" : "hidden";
    return popupFeature;
}

function addControlZoombar(){
	var mapWidth = parseInt($("#map").width());
	var zoomXPosition = parseInt(mapWidth/2.098);
	if(pzb && zoomXPosition == 474){
		return;
	}else{
		map.removeControl(pzb);
		pzb = new OpenLayers.Control.PanZoomBar({
			imgZoomin : "zoom-plus-ensun.png",
			imgZoomworld : "z_world.png",
			imgZoomout : "zoom-minus-ensun.png",
			imgZoombar : "z_orange_zoombar.png",
			imgZoomslider : "slider-orange.png"
		});
		pzb.position = new OpenLayers.Pixel(zoomXPosition+7,-23);
		map.addControl(pzb);
	}
}

mapPopControl.idToolTip = function() {
   $("#idToolTip").toggle();
};

mapPopControl.testToolTip = function(e) {
   if(!loginCheck()){alert("로그인 해주세요.");return;}
   $("#testToolTip").toggle();
};

var tabValue = 0;
var tabType = '';
mapPopControl.sanggaTabOnclick = function(imgType,val) {
	$("#sanggaView .sanggaViewContent").empty();
	$("#sangga_img_detail").attr("src","/beta/images/map/pop/sangga_tab_detail_off.gif");
	$("#sangga_img_review").attr("src","/beta/images/map/pop/sangga_tab_review_off.gif");
	$("#sangga_img_photo").attr("src","/beta/images/map/pop/sangga_tab_photo_off.gif");
	$("#sangga_img_rank").attr("src","/beta/images/map/pop/sangga_tab_rank_off.gif");
	
	if(tabType != imgType) {
		tabType = imgType;
		tabValue = 0;
	} else{
		tabValue += 1;		
	}
	
	if(val) tabValue = 0;
	
	if(tabValue%2) {
		$("#sanggaView .sanggaViewContent").hide();
	} else {
		mapPopControl.sanggaDataRequest(imgType);
		$("#sanggaView .sanggaViewContent").show();
		imgType == "review_write" || imgType == "review_view" ? imgType = "review" : imgType = imgType;
		$("#sangga_img_"+imgType).attr("src","/beta/images/map/pop/sangga_tab_"+imgType+"_on.gif");		
	}
};

mapPopControl.sanggaDataRequest = function(imgType) {
	var form = document.codeForm;
	var param = 'page='+form.page.value+'&buildingNo='+form.buildingNo.value+'&shopSerial='+form.shopSerial.value+'&shopReviewSerial='+form.shopReviewSerial.value;
	$.ajax({
		url: '/beta/sangga_'+imgType+'.action',
		dataType: 'html',
		data:param,
		timeout: 1000,
		error: function(){
			alert('시스템 오류');
		},
		success: function(data){
			$("#sanggaView .sanggaViewContent").append(data);
		}
	});
};

mapPopControl.mapTab = function(type) {
	$("#searchMode").val(type);
	var imgArr = ["home","area","use","job","month"];
	$(".map_nav img").each( function(i) {
		if (imgArr[i] == type) {
			$("#mapTab_"+imgArr[i]).attr("src","/beta/images/map/tab_"+imgArr[i]+"_on.gif");
		} else {
			$("#mapTab_"+imgArr[i]).attr("src","/beta/images/map/tab_"+imgArr[i]+"_off.gif");
		}
	});
	
	$("#container .panel").width(280);  
	$("#folderContents").show();
    $("#container .panel_btn").css({"left":280});
    $("#panel_img").attr("src","/beta/images/map/folder.png");
    $(".map_bar").css({"left":280});
    $(".map_nav").show();
    FolderImgFlag = 0;
};

mapPopControl.starStatus = function(objType,num) {
	var imgOn = "/beta/images/map/pop/star.png";
	var imgOff = "/beta/images/map/pop/star_none.png";
	
	for(var i=1;i<6;i++) {
		if (num >= i) {
			$("#"+objType+""+i+"").attr("src",imgOn);
		} else {
			$("#"+objType+""+i+"").attr("src",imgOff);			
		}
	}
};

mapPopControl.starStatusOut = function(objType,num) {
	for(var i=1;i<6;i++) {
		$("#"+objType+""+i+"").attr("src","/beta/images/map/pop/star_none.png");
	}
	var valueLength = $("#"+objType+"").attr("value");
	valueLength = valueLength / 2 * 1;
	for(var i=1;i<valueLength+1;i++) {
		$("#"+objType+""+i+"").attr("src","/beta/images/map/pop/star.png");
	}
};

mapPopControl.starStatusValue = function(objType,num) {
	var num1 = num * 2;
	var form = document.shopReviewWriteForm;
	$("#"+objType+"").attr("value",num1);
	var avg = ((eval($("#service").val()) + eval($("#equi").val()) + eval($("#quality").val())) / 3) * 10;
	avg = Math.floor(avg) / 10;
	$("#avg").empty();
	$("#avg").append(avg);
};

mapPopControl.ContentPrint = function(sm) {
	var form = document.searchForm;

	$.post('/beta/map_'+sm+'.action', { 
						  searchText : form.searchText.value
						 ,leftBounds : form.leftBounds.value
						 ,rightBounds : form.rightBounds.value
						 ,topBounds : form.topBounds.value
						 ,bottomBounds : form.bottomBounds.value
						 ,jobCategoryBig : form.jobCategoryBig.value
						 ,jobCategoryMedium : form.jobCategoryMedium.value
						 ,goodsCategoryBig : form.goodsCategoryBig.value
						 ,goodsCategoryMedium : form.goodsCategoryMedium.value
						 ,roomType : form.roomType.value
						 ,roomDepositMoney : form.roomDepositMoney.value
						 ,roomMonthlyRentMoney : form.roomMonthlyRentMoney.value
						 ,page : form.page.value
					},
		function(data){
		    $("#folderContents").empty();
		    $("#folderContents").append(data);
	});
};

function leftCloudPop(localeX, localeY, serial, markType){
	if(popupCloud){
		map.removePopup(popupCloud);
		popupCloud.destroy();
		popupCloud = null;
	}
	
	OpenLayers.Popup.FramedCloud.prototype.fixedRelativePosition = true; 
	OpenLayers.Popup.FramedCloud.prototype.relativePosition = "tr";
	
	var ll = new OpenLayers.LonLat(localeX,localeY);
	var feature = new OpenLayers.Feature(markers, ll); 
	feature.popupClass = OpenLayers.Class(OpenLayers.Popup.FramedCloud, {'autoSize': true});
	feature.data.popupContentHTML = '<div class="cloudpop" >데이터 불러오는 중..</div>';
	
	getCloudData(ll, markType, serial);
		
	feature.popup = feature.createPopup();
	popupCloud = feature.popup;
	map.addPopup(popupCloud);
	popupCloud.show();
}

//맵의 지역별 지도이동(공통함수)
function mapAreaSearch(){
    var proj4326 = new OpenLayers.Projection("EPSG:4326"); 
    var mapCenter = new OpenLayers.LonLat(map.getCenter().lon, map.getCenter().lat);
    mapCenter.transform( map.getProjectionObject(), proj4326 );
    var latlng = new google.maps.LatLng(mapCenter.lat, mapCenter.lon);
    // var latlng = new google.maps.LatLng(out_pt.x, out_pt.y);
    if (geocoder) {
    	geocoder.geocode({'latLng': latlng}, function(results, status) {
    		if (status == google.maps.GeocoderStatus.OK) {
    			if (results[1]) {
    				OpenLayers.Util.getElement('nodeList').innerHTML = 'lon : ' + map.getCenter().lon + ' lat : ' + map.getCenter().lat;
    				alert('result 1 : ' + results[1].formatted_address);
    				alert('result 2 : ' + results[2].formatted_address);
    				alert('result 3 : ' + results[3].formatted_address);
    				alert('result 4 : ' + results[4].formatted_address);
    				alert('result 5 : ' + results[5].formatted_address);
    				alert('result 6 : ' + results[6].formatted_address);
    				alert('result 7 : ' + results[7].formatted_address);
    				alert('result 8 : ' + results[8].formatted_address);
    				// alert('result 9 : ' + results[9].formatted_address);
    			} else {
    				alert("No results found");
    			}
    		} else {
    			alert("Geocoder failed due to: " + status);
    		}
    	});
    }

    /*
	$.getJSON("/beta/mapAreaCurrent.action", params, function (data, textStatus){
		if(textStatus == 'success'){
			var locale = data.localeNameList;
			
			if(locale){
				$("#guName,#dongName").parent().show();
				
				$("#siName").empty().append(locale[0].siName)
							.removeClass().addClass("nclicks(1,"+locale[0].siSerial+","+locale[0].guSerial+")");
				$("#guName").empty().append(data.localeNameList[0].guName)
							.removeClass().addClass("nclicks(2,"+locale[0].siSerial+","+locale[0].guSerial+")");
				$("#dongName").empty().append(data.localeNameList[0].dongName)
							  .removeClass().addClass("nclicks(3,"+locale[0].siSerial+","+locale[0].guSerial+")");
			}else{
				$("#siName").empty().append("대한민국");
				$("#guName,#dongName").parent().hide();
				return;
			}
		} else { 
			setMsg('잠시 후 다시 시도해주세요.');
			return;
		} 
	});
	*/
}

function getMapArea(level,siSerial,guSerial,onOffVal){
	var param = { level:level,siSerial:siSerial,guSerial:guSerial };

	$.ajax({
		url: '/beta/mapAreaLocation.action',
		dataType: 'json',
		data:param,
		timeout: 5000,
		success: function(data){
			if(data){
				var result = data.result;
				var siHtml = "<ul class=\"location_"+level+"\">";
				for(var i = 0; i < result.length; i++){
					var k = (1 + i) % 3;
					if(k == 0) k = 3;
					var onOff = (result[i].name == onOffVal) ? "on" : "";  
					siHtml += "<li class=\"col"+k+"\"><a class=\"location_move("+result[i].x+", "+result[i].y+", 1) "+onOff+"\">"+result[i].name+"</a></li>";
				}
				siHtml += "</ul>";
				$("#locater_data").empty().append(siHtml).show();
			}
		}
	});
}

function searchEvent(){
	$("#searchForm_page").val(0);
	$("#searchForm_leftBounds").val( map.getExtent().left );
	$("#searchForm_rightBounds").val( map.getExtent().right );
	$("#searchForm_topBounds").val( map.getExtent().top );
	$("#searchForm_bottomBounds").val( map.getExtent().bottom );
	$("#searchForm_lon").val( map.getCenter().lon );
	$("#searchForm_lat").val( map.getCenter().lat );
	$("#searchForm_zoom").val( map.getZoom() );
}

function tabSubmit(type){
	markersReset();
	$("#searchMode").val(type);
	mapPopControl.mapTab(type);
	mapPopControl.ContentPrint(type);
	if(type == "home") return;
  
	$('#searchForm').ajaxSubmit(tabOptions);	
}

function popupCloudDel(){
	if(popupCloud){
		map.removePopup(popupCloud);
		popupCloud.destroy();
		popupCloud = null;
	}
}

function markersReset(){
	if(markers) markers.destroy(); //영어 마커 초기화
	if(labelList.length > 0) labelList = []; //라벨 배열 초기화
	if(markerList.length > 0) markerList = []; //마커 배열 초기화
	if(popupCloud){
		map.removePopup(popupCloud);
		popupCloud.destroy();
		popupCloud = null;
	}
}

function markersNoReset(){
	if(markers) markers.destroy(); //영어 마커 초기화
	if(labelList.length > 0) labelList = []; //라벨 배열 초기화
	if(markerList.length > 0) markerList = []; //마커 배열 초기화
}

function showResponse(data)  {
	var sm = $("#searchMode").val();
	sm = sm == "home" ? data.indexMode : sm;
	
	mapPopControl.mapTab(sm);
	mapPopControl.ContentPrint(sm);
	markersReset();
	markerInit(data,sm);
}

function tabShowResponse(data){
	markerInit(data,null);
}

function markerInit(data,sm){
	var ll, popupClass, popupContentHTML, marker;
	var page = document.searchForm.page.value;
	if(sm == null) sm = $("#searchMode").val();
	
	if(page == 0) page = 1;
	var pageNav = page * 10;
	
	//marker 에 필요한 layer설정
	markers = new OpenLayers.Layer.Markers("Markers");
    map.addLayer(markers);
    
    for(k = 0; k < data.markListAll.length; k++){
        var localeX = data.markListAll[k].localeX;
        var localeY = data.markListAll[k].localeY;
        var localeSerial = data.markListAll[k].serial;
        var shopName = data.markListAll[k].shopName;
        
    	var ll = new OpenLayers.LonLat(localeX, localeY);

        if(pageNav - 9 <= k + 1 && k + 1 <= pageNav){
            marker = new OpenLayers.Marker(ll, markerIcon(17, 28, k+1),shopName);
        }else{
	        if(map.getZoom() > 9)
 	        	marker = new OpenLayers.Marker(ll, markerIcon(7, 7, null),shopName);
        }
        
        if(pageNav - 9 <= k + 1 && k + 1 <= pageNav){
    		marker.events.register("mouseover", marker, function(){mkOnOff(this,0);});
    		marker.events.register("mouseout", marker, function(){mkOnOff(this,1);});
    	}

        if(sm == "area"){
        	addLabel(ll,shopName,k);
        	marker.events.register("click", marker, mapImageClick);
        }else{
        	marker.events.register("click", marker, addPopupCloud);
        }
        markerList.push(marker);            
        markers.addMarker(marker);	 	        
    }
}

function registerCall(registType){
	if(!loginCheck()){
		login_box_open();
		return;
	}
	//registType : shop,use,job,month
	Win('registMap.action?registType='+registType,'register_pop',610,450);
}

function markerIcon(w,h,index){
	var icon;
	var size = new OpenLayers.Size(w,h);
    var offset = new OpenLayers.Pixel(-(size.w/2), -size.h);
    
	if(index){
		var formatIdx = (index%10) == 0 ? 10 : (index%10); 
		icon = new OpenLayers.Icon('/beta/images/marker/map/map_' + formatIdx + '.png',size,offset);
	}else{
		icon = new OpenLayers.Icon('/beta/images/marker/red_dot/dot.png', size, offset);
	}
    
	return icon;
}

function addLabel(ll, shopName, k){
	var objid = OpenLayers.Util.createUniqueID("LABEL_" + k + "_");
	var feature = new OpenLayers.Feature(wms, ll);
	feature.popupClass = OpenLayers.Class(OpenLayers.Popup.Anchored, {'autoSize': true});
	feature.data.popupContentHTML = '<div id="' + objid + '" class="mypopuphtml"><div class="mypopupleft"></div><div class="mypopupmid">' + shopName + '</div><div class="mypopupright"></div></div>';
	feature.popup = feature.createPopup();
	labelList.push(feature.popup);
}

function showToolTip(idx,page){
	var labelIndex = idx+(page-1)*10;
	map.addPopup(labelList[labelIndex]);
	labelList[labelIndex].show();
	document.getElementById(labelList[labelIndex].id).style.backgroundColor="transparent";
	mkOnOff(markerList[labelIndex],0);
}

function hideToolTip(idx,page){
	var labelIndex = idx+(page-1)*10;
	labelList[labelIndex].hide();
	if(labelList[labelIndex]) map.removePopup(labelList[labelIndex]);
	mkOnOff(markerList[labelIndex],1);
}

function mkOnOff(obj,onoff){
	var IconName = obj.icon.url.split("/")[obj.icon.url.split("/").length-1];
	IconName = (onoff == 0) ? IconName.replace("map_","mapon_") : IconName.replace("mapon_","map_");
	var newIconUrl = '/beta/images/marker/map/'+IconName;
	obj.icon.imageDiv.style.zIndex = (onoff == 0) ? 100 : 0;
	$(obj.icon.imageDiv).children().attr("src",newIconUrl);
}

function mapImageClick(evt){
	var mode = document.searchForm.searchMode.value;
	if(mode == "area"){
		tabValue = 0;
		tabType = '';
		popControl.shopInfoPrint('/beta/sangga_info.action?lon=' + this.lonlat.lon + '&lat=' + this.lonlat.lat);
	}
	return false;
}

function addPopupCloud(evt){
	if(popupCloud){
		map.removePopup(popupCloud);
		popupCloud.destroy();
		popupCloud = null;
	}
	var sm = $("#searchMode").val();
	
	OpenLayers.Popup.FramedCloud.prototype.fixedRelativePosition = true; 
	OpenLayers.Popup.FramedCloud.prototype.relativePosition = "tr";
	
	var feature = new OpenLayers.Feature(markers, this.lonlat); 
    feature.popupClass = OpenLayers.Class(OpenLayers.Popup.FramedCloud, {'autoSize': true});
    feature.data.popupContentHTML = '<div class="cloudpop" >데이터 불러오는 중..</div>';

    getCloudData(this.lonlat, sm);
   		
	feature.popup = feature.createPopup();
	popupCloud = feature.popup;
	map.addPopup(popupCloud);
	
	popupCloud.show();
}

function getCloudData(ll, markType, serial){
	if(!serial) serial = 0;
	var params = {serial:serial,lon:ll.lon,lat:ll.lat,markType:markType};
	 
	$.getJSON("markInfo.action", params, function (data, textStatus){
		if(textStatus == 'success'){
    		var cloudHTML = markInfoData(data,markType);
			$(".cloudpop").empty().append(cloudHTML);
		} else { 
			setMsg('잠시 후 다시 시도해주세요.');
			return;
		} 
	});
}

function markInfoData(data,markType){
	var markInfo = data.markInfo;
	var markImage = data.markImage;
	
	if(markType == "use"){
		var cloudHTML = '<div class="cloudpop_inner">';
		cloudHTML += '<h4>'+markInfo.goodsTitle+'</h4>';
		cloudHTML += '<span class="close" onclick="popupCloud.toggle();"></span>';
		cloudHTML += '<div class="contents">';
		cloudHTML += '<div class="info">';
		cloudHTML += "닉네임 : <a href=\"#\" onclick=\"popControl.idCardPrint('"+markInfo.goodsUserId+"');return false;\"><strong>"+markInfo.goodsUserNickName+"</strong></a><br/>";
		cloudHTML += '분류 : '+markInfo.goodsCategoryBigName+' > '+markInfo.goodsCategoryMediumName+'<br/>';
		cloudHTML += '물품명 : ['+markInfo.goodsTopTitle+'] <strong>'+markInfo.goodsProductName+'</strong><br/>';
		cloudHTML += '희망가격 : <span class="num red"><strong>'+Format_comma(markInfo.goodsPrice)+'</strong></span> 원<br/>';
		cloudHTML += '등록일 : <span class="num">'+markInfo.goodsRegdateString.split("-").join(".")+'</span><br/>';
		cloudHTML += '</div>';
		cloudHTML += '<table class="img_list">';
		cloudHTML += '<tr>';
		for(var i = 0;i < markImage.length;i++){
			cloudHTML += '<td width="55"><img src="/upload/image/small/'+markImage[i]+'" width="52" height="52" alt=""/></td>';
		}
		for(var j = 0;j < 5 - i;j++){
			cloudHTML += '<td width="55">&nbsp;</td>';
		}
		cloudHTML += '<tr>';
		cloudHTML += '</table>';
		cloudHTML += '<span class="right_btn">상세보기</span>';
		cloudHTML += '</div>';
		cloudHTML += '</div>';
	}else if(markType == "month"){
		var cloudHTML = '<div class="cloudpop_inner">';
		cloudHTML += '<h4>'+markInfo.roomTitle+'</h4>';
		cloudHTML += '<span class="close" onclick="popupCloud.toggle();"></span>';
		cloudHTML += '<div class="contents">';
		cloudHTML += '<div class="info">';
		cloudHTML += '형태 : <strong>'+markInfo.roomType+'</strong><br/>';
		cloudHTML += '방평수 : <strong>'+markInfo.roomSpace+'</strong> 평<br/>';
		cloudHTML += '가격 : 보 <span class="red"><strong>'+markInfo.roomDepositMoney+'</strong></span> / 월 <span class="red"><strong>'+markInfo.roomMonthlyRentMoney+'</strong></span><br/>';
		cloudHTML += '옵션 : '+markInfo.roomFurniture+','+markInfo.roomHeating+'<br/>';
		cloudHTML += '위치 : '+markInfo.roomAddress+'<br/>';
		cloudHTML += '</div>';
		cloudHTML += '<div class="cont">'+markInfo.roomConditioning+'</div>';
		cloudHTML += '<table class="img_list">';
		cloudHTML += '<tr>';
		cloudHTML += '<td><img src="/beta/images/map/month_ex.gif" width="52" height="52" alt=""/></td>';
		cloudHTML += '<td><img src="/beta/images/map/month_ex.gif" width="52" height="52" alt=""/></td>';
		cloudHTML += '<td><img src="/beta/images/map/month_ex.gif" width="52" height="52" alt=""/></td>';
		cloudHTML += '<td><img src="/beta/images/map/month_ex.gif" width="52" height="52" alt=""/></td>';
		cloudHTML += '<td><img src="/beta/images/map/month_ex.gif" width="52" height="52" alt=""/></td>';
		cloudHTML += '<tr>';
		cloudHTML += '</table>';
		cloudHTML += '<span class="right_btn">동네이야기</span>';
		cloudHTML += '</div>';
		cloudHTML += '</div>';
	}else{
		var cloudHTML = '<div class="cloudpop_inner">';
		cloudHTML += '<h4>'+markInfo.jobTitle+'</h4>';
		cloudHTML += '<span class="close" onclick="popupCloud.toggle();"></span>';
		cloudHTML += '<div class="contents">';
		cloudHTML += '<div class="job_info">';
		cloudHTML += '<span class="img"><img src="/beta/images/map/job_ex.gif"/></span>';
		cloudHTML += '업체명 : <strong>'+markInfo.jobCompanyName+'</strong><br/>';
		cloudHTML += '근무시간 : '+markInfo.jobTime+'<br/>';
		cloudHTML += '근무요일 : '+markInfo.jobDay+'<br/>';
		cloudHTML += '급여 : <span class="red"><strong>'+markInfo.jobPay+'원</strong></span><br/>';
		cloudHTML += '업무내용 : '+markInfo.jobBiz+'<br/>';
		cloudHTML += '자격 : 나이 '+markInfo.jobAge+'살, 성별 '+markInfo.jobSex+'<br/>';
		cloudHTML += '연락처 : '+markInfo.jobTel+'<br/>';
		cloudHTML += '</div>';
		cloudHTML += '<div class="job_cont">'+markInfo.jobContents+'</div>';
		cloudHTML += '<span class="right_btn">동네이야기</span>';
		cloudHTML += '</div>';
		cloudHTML += '</div>';
	}
	return cloudHTML;
}